﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace CommonUtils
{
    public static class ControlFinder
    {
        /// <summary>
        /// Similar to Control.FindControl, but recurses through child controls.
        /// </summary>
        public static T FindControl<T>(Control startingControl, string id) where T : Control
        {
            try
            {
                T found = startingControl.FindControl(id) as T;

                if (found == null)
                {
                    found = FindChildControl<T>(startingControl, id);
                }

                return found;
            }
            catch (Exception e)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(e, "Error", CommonUtilsSettings.Default.ApplicationName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", e);
            }
        }

        /// <summary>     
        /// Similar to Control.FindControl, but recurses through child controls.
        /// Assumes that startingControl is NOT the control you are searching for.
        /// </summary>
        public static T FindChildControl<T>(Control startingControl, string id) where T : Control
        {
            try
            {
                T found = null;
                foreach (Control activeControl in startingControl.Controls)
                {
                    found = activeControl as T;
                    if (found == null || (string.Compare(id, found.ID, true) != 0))
                    {
                        found = FindChildControl<T>(activeControl, id);
                    }
                    if (found != null)
                    {
                        break;
                    }
                }
                return found;
            }
            catch (Exception e)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(e, LogStatus.Error, CommonUtilsSettings.Default.ApplicationName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", e);
            }
        }
    }
}
